#include "TaskPanelController.h"
#include "PlanWidget.h"
#include "PlanService.h"
#include "ConfigService.h"
#include "plan/PlanTask.h"
#include <QPushButton>
#include <QShortcut>
#include <QDate>
#include <QDebug>

TaskPanelController::TaskPanelController(QObject* parent)
    : QObject(parent)
{
}

TaskPanelController::~TaskPanelController()
{
}

// [API-002][AC-004] 绑定 PlanWidget 并连接 PlanService 信号
bool TaskPanelController::bindPlanWidget(PlanWidget* widget)
{
    if (!widget) {
        qCritical() << "[E003_WIDGET_NULL] PlanWidget pointer is null";
        return false;
    }
    
    m_planWidget = widget;
    
    // 设置为紧凑模式
    m_planWidget->setCompactMode(true);
    
    // 连接 PlanService 信号 -> PlanWidget 刷新
    auto& planService = PlanService::instance();
    
    connect(&planService, &PlanService::tasksUpdated,
            this, &TaskPanelController::onPlanServiceTasksUpdated);
    
    connect(&planService, &PlanService::taskCreated,
            this, &TaskPanelController::onPlanServiceTaskCreated);
    
    connect(&planService, &PlanService::taskDeleted,
            this, &TaskPanelController::onPlanServiceTaskDeleted);
    
    qDebug() << "[TaskPanelController] PlanWidget bound successfully";
    return true;
}

// [API-003][AC-002][AC-003] 持久化状态
bool TaskPanelController::persistState(bool expanded)
{
    try {
        ConfigService::instance().setTaskPanelExpanded(expanded);
        qDebug() << "[TaskPanelController] State persisted:" << expanded;
        return true;
    } catch (const std::exception& e) {
        qCritical() << "[E004_CONFIG_WRITE_FAILED]" << e.what();
        
        // 降级：仅内存状态
        m_fallbackState = expanded;
        return false;
    } catch (...) {
        qCritical() << "[E004_CONFIG_WRITE_FAILED] Unknown exception";
        m_fallbackState = expanded;
        return false;
    }
}

void TaskPanelController::bindToggleSources(QPushButton* btn, QShortcut* shortcut)
{
    // 按钮和快捷键的连接将在 DesktopTimer 中完成
    Q_UNUSED(btn);
    Q_UNUSED(shortcut);
}

// [AC-003] 从配置恢复状态
void TaskPanelController::restoreState()
{
    bool expanded = ConfigService::instance().getTaskPanelExpanded();
    qDebug() << "[TaskPanelController] Restoring state:" << expanded;
    emit stateChanged(expanded);
}

// [AC-004] PlanService 信号桥接 - 200ms 内刷新
void TaskPanelController::onPlanServiceTasksUpdated(const QDate& date)
{
    if (m_planWidget && date == QDate::currentDate()) {
        m_planWidget->refreshTasks();
    }
}

void TaskPanelController::onPlanServiceTaskCreated(const PlanTask& task)
{
    Q_UNUSED(task);
    if (m_planWidget) {
        m_planWidget->refreshTasks();
    }
}

void TaskPanelController::onPlanServiceTaskDeleted(const QString& taskId, const QDate& date)
{
    Q_UNUSED(taskId);
    if (m_planWidget && date == QDate::currentDate()) {
        m_planWidget->refreshTasks();
    }
}
